<template>
  <view class="createContract">
    <u-navbar
      :background="navbar.background"
      :border-bottom="false"
      :title-color="navbar.color"
      back-icon-color="#fff"
      :title="$t('创建合同')"
      title-width="300"
    >
      <view slot="right">
        <view style="width: 70rpx; color: #fff" @click="sendFn">{{$t('提交')}}</view>
      </view>
    </u-navbar>
    <u-form ref="uForm" :model="ruleForm" label-width="180">
      <u-form-item
        :border-bottom="ruleForm.file.length > 0 ? false : true"
        :label="$t('上传合同')"
        prop="file"
        required
      >
        <view style="color: #888">{{$t('只支持上传PDF')}}</view>
        <u-button
          slot="right"
          :disabled="ruleForm.file.length > 0"
          size="mini"
          type="primary"
          @click="createUpload"
        >
          {{$t('选取')}}
        </u-button>
      </u-form-item>
      <u-form-item v-if="ruleForm.file.length > 0">
        <uni-list :border="false">
          <uni-list-item
            v-for="(item, index) in ruleForm.file"
            :key="index"
            :border="false"
            :title="item.name"
            clickable
            style="width: 100%"
          >
            <view slot="footer" style="color: #888; display: flex; align-items: center">
              <u-icon name="close-circle" size="40" @click="ruleForm.file = []"></u-icon>
            </view>
          </uni-list-item>
        </uni-list>
      </u-form-item>
      <u-form-item :label="$t('申请单名称')" prop="title" required>
        <u-input v-model="ruleForm.title" border type="text" />
      </u-form-item>
      <u-form-item :label="$t('所属企业')" prop="enterpriseName" required>
        <u-input
          v-model="ruleForm.enterpriseName"
          :clearable="false"
          :select-open="select.title === '所属企业' && select.show"
          border
          type="select"
          @clear="inputSelect('所属企业')"
          @click="showSelect('所属企业')"
        />
      </u-form-item>
      <u-form-item
        :border-bottom="ruleForm.file.length > 0 ? false : true"
        :label="$t('签署方')"
        prop="enterpriseName"
        required
      >
        <view slot="right">
          <u-checkbox-group>
            <u-checkbox v-model="ruleForm.isOrder">{{$t('顺序签署')}}</u-checkbox>
          </u-checkbox-group>
          <u-button plain size="mini" type="primary" @click="addUser">{{$t('已有签署方')}}</u-button>
        </view>
      </u-form-item>
      <u-form-item v-if="secondPartyValidList.length > 0">
        <uni-list :border="false">
          <uni-list-item
            v-for="(item, index) in secondPartyValidList"
            :key="index"
            :border="false"
            clickable
            style="width: 100%; padding: 0"
          >
            <view slot="body" class="lz-list-body" style="padding: 0">
              <view class="lz-list-item lz-ellipsis-1">
                {{$t('签署类型')}}：
                <u-radio-group v-model="item.signType">
                  <u-radio name="sign">{{$t('签名')}}</u-radio>
                  <u-radio name="send">{{$t('抄送')}}</u-radio>
                </u-radio-group>
              </view>
              <view class="lz-list-item lz-ellipsis-1">{{$t('签约方名称')}}：{{ item.partnerName }}</view>
              <view class="lz-list-item lz-ellipsis-1">
                {{$t('证件类型')}}：{{ computerDocumentType(item.identTypeCode) }}
              </view>
              <view class="lz-list-item lz-ellipsis-1">{{$t('证件号码')}}：{{ item.identNo }}</view>
              <view class="lz-list-item lz-ellipsis-1">{{$t('手机号')}}：{{ item.phone }}</view>
            </view>
            <view slot="footer" class="lz-list-footer">
              <u-button
                :disabled="item.isDel === false"
                size="mini"
                type="primary"
                @click="customerDelete(item)"
              >
                {{$t('删除')}}
              </u-button>
            </view>
          </uni-list-item>
        </uni-list>
      </u-form-item>

      <u-form-item :label="$t('签署截止日期')" prop="expireTime" required>
        <u-input
          v-model="ruleForm.expireTime"
          :select-open="picker.show"
          border
          type="select"
          @clear="clearTime('截止日期')"
          @click="checkTime('截止日期')"
        />
      </u-form-item>
      <u-form-item :label="$t('发送链接')" prop="sendRemind">
        <view slot="right">
          <u-checkbox-group>
            <u-checkbox v-model="ruleForm.sendRemind">{{$t('向签名人发送签署链接')}}</u-checkbox>
          </u-checkbox-group>
        </view>
      </u-form-item>
    </u-form>
    <u-select
      v-model="select.show"
      :filterable="select.filterable"
      :label-name="select.label"
      :list="select.list"
      :value-name="select.value"
      @confirm="confirmSelet"
    ></u-select>
    <u-picker
      v-model="picker.show"
      :params="picker.params"
      mode="time"
      @confirm="pickerendshowFn"
    ></u-picker>
    <l-file ref="lFile" top="0rpx" @up-success="upSuccess"></l-file>
  </view>
</template>
<script>
import { mapGetters, mapMutations } from 'vuex'

export default {
  computed: {
    ...mapGetters(['userInfo', 'api', 'userToken', 'documentTypeList']),
    computerDocumentType() {
      return (code) => {
        let item = this.documentTypeList.find((item) => item.value === code)
        return item.label
      }
    }
  },
  data() {
    return {
      navbar: {
        color: '#fff',
        background: {
          backgroundColor: '#0079FF'
        }
      },
      ruleForm: {
        file: [], //上传的附件
        title: '', //合同标题
        enterpriseName: '', //所属企业
        enterpriseId: '', //所属企业id
        expireTime: '', //截止日期
        isOrder: false,
        sendRemind: true //发送链接
      },
      rules: {
        file: [
          {
            validator: (rule, value, callback) => {
              return this.ruleForm.file.length > 0
            },
            message: this.$t('必填'),
            trigger: ['change']
          }
        ],
        title: [{ required: true, message: this.$t('必填'), trigger: ['change'] }],
        enterpriseName: [{ required: true, message: this.$t('必填'), trigger: ['change'] }],
        expireTime: [{ required: true, message: this.$t('必填'), trigger: ['change'] }]
      },
      enterpriseList: [], //企业列表
      select: {
        title: '',
        show: false,
        list: [],
        value: 'value',
        label: 'label',
        filterable: true
      },
      picker: {
        show: false,
        params: {
          year: true,
          month: true,
          day: true,
          hour: true,
          minute: true,
          second: true,
          // 选择时间的时间戳
          timestamp: true
        }
      },
      secondPartyValidList: [] //签署方列表
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
  onLoad(op) {
    //查询企业列表
    this.getEnterpriseList()
  },
  methods: {
    //提交
    sendFn() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          if (this.secondPartyValidList.length === 0) {
            uni.showToast({
              title: this.$t('签约方不能为空'),
              icon: 'none'
            })
            return
          }
          //过滤掉甲方的数据（留下乙方）
          let arr = this.secondPartyValidList.filter((item) => {
            if (item.isFirstParty === true) {
              this.ruleForm.signType = item.signType
            } else {
              return item
            }
          })
          let req = {
            secondPartyValidList: arr, //签约方(乙方)列表
            order: this.ruleForm.isOrder, //是否顺序签署
            title: this.ruleForm.title, //合同标题
            fileIds: [this.ruleForm.file[0].fileId], //合同文件id列表
            enterpriseId: this.ruleForm.enterpriseId, //甲方企业id
            signType: this.ruleForm.signType, //甲方签署方式（抄送还是签名）
            expireTime: this.ruleForm.expireTime, //签署截止时间
            sendRemind: this.ruleForm.sendRemind //向签名人发送提醒  false:否  true:是
          }
          this.$u
            .post(this.api.GLOBAL_electronic_contract_create, req, {
              'content-type': 'application/json;charset=UTF-8'
            })
            .then((res) => {
              uni.hideLoading()
              if (res.code === 200) {
                uni.showToast({
                  title: res.msg
                })
                setTimeout(() => {
                  uni.$emit('applicationDetailsToApplicationList', true)
                  uni.navigateBack({
                    delta: 1
                  })
                }, 1000)
              }
            })
        }
      })
    },

    //删除
    customerDelete(row) {
      this.secondPartyValidList = this.secondPartyValidList.filter((item) => {
        return item.id !== row.id
      })
    },
    //已有签署方
    addUser() {
      if (this.secondPartyValidList.length === 0) {
        //console.log(this.secondPartyValidList);
        uni.showToast({
          title: this.$t('请先选择所属企业'),
          icon: 'none'
        })
        return
      }
      //过滤掉甲方的数据（留下乙方）
      let arr = this.secondPartyValidList
        .filter((item) => {
          if (item.isFirstParty !== true) {
            return item
          }
        })
        .map((item) => {
          return item.id
        })
      //console.log(arr);
      uni.navigateTo({
        url: '../../electronicSeal/signatoriesList/signatoriesList',
        events: {
          confirm(data) {
            //console.log(data);
            // type 签约方类型  自选企业:enterprise   企业签署方:party   签署联系人:person
            let result = {
              ...data,
              type: 'party',
              signType: 'sign', //签名sign和抄送send
              order: '' //序号
            }
            this.userFn(result)
          }
        },
        success(res) {
          res.eventChannel.emit('pagePramas', {
            enterpriseId: this.secondPartyValidList[0].id,
            oldSelectList: arr,
            type: '已有签署方'
          })
        }
      })
    },
    userFn(data) {
      this.secondPartyValidList.push(data)
      let obj = {}
      this.secondPartyValidList = this.secondPartyValidList.reduce((item, next) => {
        obj[next.id] ? '' : (obj[next.id] = true && item.push(next))
        return item
      }, [])
    },
    //清除日期
    clearTime() {
      this.ruleForm.expireTime = ''
    },
    //选取日期
    checkTime() {
      this.picker.show = true
    },
    //日期
    pickerendshowFn(e) {
      this.ruleForm.expireTime =
        e.year + '-' + e.month + '-' + e.day + ' ' + e.hour + ':' + e.minute + ':' + e.second
    },
    //清空选项
    inputSelect(title) {
      if (title === '所属企业') {
        this.ruleForm.enterpriseId = '' //企业id
        this.ruleForm.enterpriseName = '' //所属企业名
      }
    },
    //选择企业
    confirmSelet(e) {
      if (this.select.title === '所属企业') {
        this.ruleForm.enterpriseId = e[0].value //企业id
        this.ruleForm.enterpriseName = e[0].label //所属企业名
        //找到当前选项所有数据
        let obj = this.enterpriseList.find((item) => item.id === e[0].value)
        //切换企业
        this.changeEnterprise(obj)
      }
    },
    //切换企业
    changeEnterprise(row) {
      //不允许删除
      row.isDel = false
      row.type = 'enterprise' // type 签约方类型  自选企业:enterprise   企业签署方:party   签署联系人:person
      row.signType = 'sign' //签名sign和抄送send
      row.order = ''
      row.isFirstParty = true //是否甲方
      row.partnerName = row.name
      row.phone = row.mobilePhone
      let obj = JSON.parse(JSON.stringify(row))
      this.secondPartyValidList = [obj]
    },
    //选择select
    showSelect(title) {
      this.select.show = true
      this.select.title = title
      if (title === '所属企业') {
        this.select.list = this.enterpriseList
        this.select.label = 'name'
        this.select.value = 'id'
      }
    },
    //查询企业列表
    getEnterpriseList() {
      let req = {
        page: false
      }
      this.$u
        .get(this.api.GLOBAL_electronic_enterprise_findList, req, {
          'content-type': 'application/json'
        })
        .then((res) => {
          if (res.code === 200 && res.data) {
            this.enterpriseList = res.data
          } else {
            this.enterpriseList = []
          }
        })
    },
    //上传文件成功
    upSuccess(res) {
      //console.log(res);
      this.ruleForm.file = [res.data.id]
    },
    //选取
    createUpload() {
      /*
      选择文件并上传
      currentWebview=当前窗口，仅app端需要传，且必传
      url=上传服务器地址，必填
      name=上传文件的key(选填，默认为file)
      header=请求头(选填)
      filetypes：为支持选取的格式数组默认["jpg","jpeg","png","rar","txt","zip","doc","ppt","xls","pdf","docx","xlsx","mp4","wmv","avi","mp3","m4a","wma",
            "JPG","JPEG","PNG","RAR","TXT","ZIP","DOC","PPT","XLS","PDF","DOCX","XLSX","MP4","WMV","AVI","MP3","M4A","WMA"]
      */
      this.$refs.lFile.upload({
        // #ifdef APP-PLUS
        // nvue页面使用时请查阅nvue获取当前webview的api，当前示例为vue窗口
        currentWebview: this.$mp.page.$getAppWebview(),
        // #endif
        url:
          uni.getStorageSync('baseUrl') +
          this.api.GLOBAL_electronic_contract_file_uploadContractFile, //如果不跨越默认上传接口file
        //默认file,上传文件的key
        name: 'file',
        header: {
          Authorization: this.userToken,
          us: 'app'
        },
        filetypes: ['pdf', 'PDF'],
        crossDomain: {
          //为了解决ios跨域问题
          name: '检测跨域',
          src1: uni.getStorageSync('baseUrl') + this.api.GLOBAL_auth_org_getOrgsByPhone, //用于检测跨域的
          src2:
            uni.getStorageSync('baseUrl') +
            this.api.GLOBAL_app_electronic_contract_file_uploadContractFileBase64Code //如果跨域，则调用此接口，苹果跨越上传beas64
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.createContract {
  padding: 0 30rpx;
}
</style>
